import { getUrlCode } from "@/common/js/util.js"
import { request } from '@/common/js/request.js'
import { conf as mpConf } from '@/platform/api/conf/mp.js'

export function authLogin(mode, callback_page) {
	mpConf().then(res => {
		var appid = res.data.appid
		let href = window.location.href
		var url = new URL(href)
		var local = encodeURIComponent(url.origin + callback_page); // 当前H5页面的url

		var wxUrl =
			'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			appid +
			'&redirect_uri=' +
			local +
			'&response_type=code' +
			'&scope=snsapi_' + (mode === 'userinfo' ? 'userinfo' : 'base') +
			'&state=STATE#wechat_redirect';
		window.location.href = wxUrl;
	}).catch(err => {
		console.log("获取code失败")
	})
}

export function login() {
	return new Promise((resolve, reject) => {
		const url_params = getUrlCode()
		const openid = url_params.openid
		if (openid !== '' && openid != null && openid != undefined) {
			request('/auth/mp/openid', {
				openid: openid
			}, 'POST').then(res => {
				//成功回调
				if (res.errorCode == 200) {
					uni.setStorageSync('token', res.data.token);
					resolve(res);
				} else {
					reject('non login!');
				}
			}).catch(err => {
				//请求失败
				console.log("openid 登入失败！")
				reject(err)
			})
		} else {
			const code = url_params.code;
			if (code !== null && code !== '' && code !== undefined) {
				request('/auth/mp/code', {
					code: code
				}, 'POST').then(res => {
					if (res.errorCode == 200) {
						uni.showToast({
							title: '微信登入成功',
							icon: 'none'
						})
						uni.setStorageSync('token', res.data.token);
						resolve(res);
					} else {
						console.log(res)
						reject('non login!');
					}
				}).catch(err => {
					console.log("login error: code2session 错误!")
					reject('code auth error')
				})
			} else {
				reject('no code')
			}
		}
	})
}
